package com.ptrsystem.siatd.dao.implementacion;

import com.ptrsystem.siatd.beans.Annio;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class MantenimientoAnnioImplement implements com.ptrsystem.siatd.dao.interfaces.MantenimientoAnnioInterface {

    @Autowired
    private DataSource dataSource;

    @Override
    @Transactional
    public boolean getRegistraAnio(Annio anio) {
        boolean rt = false;
        JdbcTemplate jdbc = new JdbcTemplate(this.dataSource);
        int rs = jdbc.update("insert into TD_ANNIO values(?,?)",
                anio.getCodAnio(), anio.getAnio());
        if (rs > 0) {
            rt = !rt;
        }
        return rt;
    }

    @Override
    public List<Annio> getListaAnio() {
        JdbcTemplate jdbc = new JdbcTemplate(this.dataSource);
        List<Annio> lista = jdbc.query("select * from TD_ANNIO", new rowMapper());
        return lista;
    }

    @Override
    public int getGeneraCodAnio() {
        String rs = "0";
        JdbcTemplate jdbc = new JdbcTemplate(this.dataSource);
        rs = jdbc.queryForObject("select convert(int,(MAX(COD_ANNIO))) from TD_ANNIO", String.class);
        if (rs == null) {
            rs = "0";
        }
        int rt = Integer.parseInt(rs);
        rt += 1;
        return rt;
    }

    private class rowMapper implements RowMapper<Annio> {

        @Override
        public Annio mapRow(ResultSet rs, int i) throws SQLException {
            Annio anio = new Annio(rs.getString(1), rs.getString(2));
            return anio;
        }
    }

}
